<template>
  <div class="order-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>订单管理</span>
          <div class="header-actions">
            <el-input
              v-model="searchText"
              placeholder="搜索订单号"
              style="width: 200px; margin-right: 10px;"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button @click="handleSearch">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
            <el-select
              v-model="statusFilter"
              placeholder="订单状态"
              style="width: 120px; margin-right: 10px;"
              clearable
              @change="handleStatusFilter"
            >
              <el-option label="待付款" value="pending" />
              <el-option label="已付款" value="paid" />
              <el-option label="已发货" value="shipped" />
              <el-option label="已完成" value="completed" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
            <el-button @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="orderList" v-loading="loading" stripe>
        <el-table-column prop="orderNo" label="订单号" width="180" />
        
        <el-table-column prop="userInfo.nickName" label="用户" width="120" />
        
        <el-table-column prop="products" label="商品信息" min-width="200">
          <template #default="scope">
            <div v-for="item in scope.row.products" :key="item.productId" class="product-item">
              {{ item.name }} × {{ item.quantity }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="totalAmount" label="订单金额" width="120" align="center">
          <template #default="scope">
            <span class="amount">¥{{ scope.row.totalAmount }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="订单状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="下单时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleViewDetail(scope.row)">
              详情
            </el-button>
            <el-button 
              v-if="scope.row.status === 'paid'"
              size="small" 
              type="primary" 
              @click="handleShip(scope.row)"
            >
              发货
            </el-button>
            <el-button 
              v-if="scope.row.status === 'pending'"
              size="small" 
              type="danger" 
              @click="handleCancel(scope.row)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'

const orderList = ref([])
const loading = ref(false)
const searchText = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 模拟数据
const mockOrders = [
  {
    _id: '1',
    orderNo: 'ORD202401010001',
    userInfo: { nickName: '张三' },
    products: [
      { productId: '1', name: '优AI文化纪念T恤', quantity: 2 },
      { productId: '2', name: '文化活动纪念册', quantity: 1 }
    ],
    totalAmount: 203.00,
    status: 'paid',
    createTime: '2024-01-01T10:30:00.000Z'
  },
  {
    _id: '2',
    orderNo: 'ORD202401010002',
    userInfo: { nickName: '李四' },
    products: [
      { productId: '3', name: '限量版徽章套装', quantity: 1 }
    ],
    totalAmount: 45.00,
    status: 'shipped',
    createTime: '2024-01-01T14:20:00.000Z'
  },
  {
    _id: '3',
    orderNo: 'ORD202401010003',
    userInfo: { nickName: '王五' },
    products: [
      { productId: '1', name: '优AI文化纪念T恤', quantity: 1 }
    ],
    totalAmount: 89.00,
    status: 'pending',
    createTime: '2024-01-01T16:45:00.000Z'
  }
]

const getOrderList = async () => {
  loading.value = true
  try {
    // 这里应该调用实际的API
    // const result = await CloudBaseAPI.getOrderList(currentPage.value, pageSize.value, searchText.value, statusFilter.value)
    
    // 模拟API调用
    setTimeout(() => {
      let filteredOrders = mockOrders
      if (statusFilter.value) {
        filteredOrders = mockOrders.filter(order => order.status === statusFilter.value)
      }
      if (searchText.value) {
        filteredOrders = filteredOrders.filter(order => 
          order.orderNo.includes(searchText.value)
        )
      }
      
      orderList.value = filteredOrders
      total.value = filteredOrders.length
      loading.value = false
    }, 500)
  } catch (error) {
    ElMessage.error('获取订单列表失败')
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  getOrderList()
}

const handleStatusFilter = () => {
  currentPage.value = 1
  getOrderList()
}

const handleRefresh = () => {
  searchText.value = ''
  statusFilter.value = ''
  currentPage.value = 1
  getOrderList()
}

const handlePageChange = () => {
  getOrderList()
}

const handleSizeChange = () => {
  currentPage.value = 1
  getOrderList()
}

const handleViewDetail = (order) => {
  ElMessage.info('查看订单详情功能开发中...')
}

const handleShip = (order) => {
  ElMessage.info('订单发货功能开发中...')
}

const handleCancel = (order) => {
  ElMessage.info('取消订单功能开发中...')
}

const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

const getStatusType = (status) => {
  const statusMap = {
    'pending': 'warning',
    'paid': 'primary',
    'shipped': 'success',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'pending': '待付款',
    'paid': '已付款',
    'shipped': '已发货',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || '未知'
}

onMounted(() => {
  getOrderList()
})
</script>

<style scoped>
.order-management {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.product-item {
  margin-bottom: 4px;
  font-size: 12px;
  color: #666;
}

.amount {
  color: #f56c6c;
  font-weight: 600;
}
</style>